package mapper

import (
	"errors"
	"fmt"
	"im/global"
	"im/model"
	"im/utils"

	"gorm.io/gorm"
)

type UserMapper struct{}

// 登录
func Login(u *model.User) (*model.User, error) {
	var user model.User
	err := global.DB.Where("name = ?", u.Name).First(&user).Error
	pwd := utils.Md5Password(u.Password, u.Salt)
	if err != nil && user.Password != pwd {
		return u, errors.New("用户密码错误")
	}
	return &user, err
}

func GetUserList() []*model.User {
	ub := make([]*model.User, 10)
	global.DB.Find(&ub)
	for _, v := range ub {
		fmt.Printf("v: %v\n", v)
	}
	return ub
}

/**
创建
*/
func CreateUser(user model.User) *gorm.DB {
	return global.DB.Create(&user)
}

func DeleteUserById(id uint) {
	global.DB.Delete(&model.User{}, "id = ?", id)
}

func GetUserById(id uint) (model.User, error) {
	var userBasic model.User
	return userBasic, global.DB.Model(&userBasic).Where("id = ?", id).Find(&userBasic).Error
}

func UserUpdate(userBasic *model.User) (model.User, error) {
	return *userBasic, global.DB.Updates(userBasic).Error
}

func FindUserByPhoneNum(phoneNum string) (model.User, error) {
	var userBasic model.User
	return userBasic, global.DB.Model(&userBasic).Where("phone = ?", phoneNum).First(&userBasic).Error
}

func FindUserByName(name string) (model.User, error) {
	var userBasic model.User
	return userBasic, global.DB.Model(&userBasic).Where("name = ?", name).First(&userBasic).Error
}
